package com.example.mysample.dubbo;

import com.example.mysample.dubbo.spi.BMWCar;
import com.example.mysample.dubbo.spi.Car;
import com.example.mysample.dubbo.spi.Driver;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @author YangXu
 * @date 2022/10/1
 * @description:
 */
public class SPITest {

    //测试代码
    @Test
    public void testJava(){
        ServiceLoader<Car> serviceLoader = ServiceLoader.load(Car.class);
        Iterator<Car> iterator = serviceLoader.iterator();
        while (iterator.hasNext()){
            Car car = iterator.next();
            if("com.example.mysample.dubbo.spi.BMWCar".equals(car.getClass().getName())){
                car.run(null);
            }
        }
    }

    @Test
    public void testDubbo(){
        Car bmw = ApplicationModel.defaultModel()
                .getExtensionDirector().getExtension(Car.class, "bmw");
        bmw.run(null);
    }

    /**
     * 使用Dubbo SPI实现IOC，需要引入一个URL（服务总线）的概念，
     * 其中包括我们后面要用到的很多关于Dubbo应用配置，如协议，端口，参数配置等！
     */
    @Test
    public void testIOC() {
        Driver oldDriver = ApplicationModel.defaultModel()
                .getExtensionDirector().getDefaultExtension(Driver.class);
        Map<String, String> map = new HashMap<>();
        map.put("carType", "bmw");
        URL bmw = new URL(null, null, 0, map);

        oldDriver.driverCar(bmw);
    }
}
